/*
 * CellSymmetry.h
 *
 *  Created on: Jun 8, 2011
 *      Author: marchi
 */

#ifndef CELLSYMMETRY_H_
#define CELLSYMMETRY_H_
#include "gmx_polar.h"
#include "AtomIndex.h"

using std::cout;
using std::endl;
class CellSymmetry {
	t_topology *top;
	t_trxframe *fr;
	t_pbc *pbc;
	rvec * x_ref;
	gmx_rmpbc_t  gpbc;
	CellSymmetry(){};
	void Gpbc(){
		if (gpbc != NULL)
			gmx_rmpbc_done(gpbc);
	}
public:
	CellSymmetry(t_topology * its_top, t_trxframe * its_fr,t_pbc * its_pbc){
		top=its_top;
		fr=its_fr;
		pbc=its_pbc;
		gpbc=NULL;
		x_ref=NULL;
	}
	CellSymmetry & operator()(t_topology * its_top, t_trxframe * its_fr,t_pbc * its_pbc){
		top=its_top;
		fr=its_fr;
		pbc=its_pbc;
		gpbc=NULL;
		x_ref=NULL;
		return *this;
	}
	void Xref(){
	x_ref=new rvec [natoms];
	for(int i=0;i<natoms;i++){
		x_ref[i][XX]=fr->x[i][XX];
		x_ref[i][YY]=fr->x[i][YY];
		x_ref[i][ZZ]=fr->x[i][ZZ];
		}
	}
	void Center(){
		int ecenter=0;
		int ePBC;

		int unitcell_enum=euCompact;

		ePBC=fr->ePBC;
		set_pbc(pbc,ePBC,fr->box);
		gpbc = gmx_rmpbc_init(&top->idef,ePBC,fr->natoms,fr->box);
		gmx_rmpbc_trxfr(gpbc,fr);
		put_molecule_com_in_box(unitcell_enum,ecenter,
				&top->mols,fr->natoms,top->atoms.atom,ePBC,fr->box,fr->x);
		reset_x(nindex,cindex, natoms, NULL,fr->x,w_lst);
		center_x(0,fr->x,fr->box,fr->natoms,nindex,cindex);
		Gpbc();
	}
	void Center1(AtomIndex &);

	void Center0(int nindex0, atom_id * cindex0){

		int ecenter=0;
		int ePBC;

		int unitcell_enum=euCompact;

		ePBC=fr->ePBC;
		set_pbc(pbc,ePBC,fr->box);

		put_molecule_com_in_box(unitcell_enum,ecenter,
				&top->mols,fr->natoms,top->atoms.atom,ePBC,fr->box,fr->x);

		reset_x(nindex0,cindex0, natoms, NULL,fr->x,w_lst);

		center_x(0,fr->x,fr->box,fr->natoms,nindex0,cindex0);
	}

	void Mypbc(){
		int ePBC;
		ePBC=fr->ePBC;
		set_pbc(pbc,ePBC,fr->box);
		gpbc = gmx_rmpbc_init(&top->idef,ePBC,fr->natoms,fr->box);
		gmx_rmpbc_trxfr(gpbc,fr);
		Gpbc();
	}
	void Fit(){
		if(!x_ref) {
			Xref();
		}
		matrix R;
		calc_fit_R(DIM,natoms,w_lst,x_ref,fr->x,R);
	}

	virtual ~CellSymmetry(){top=NULL;fr=NULL;pbc=NULL;x_ref=NULL; delete [] x_ref;};
};

#endif /* CELLSYMMETRY_H_ */
